//
//  LoginAlertView.swift
//  MIFI
//
//  Created by 金嗓子卡卡 on 2019/4/21.
//  Copyright © 2019 NJMifi. All rights reserved.
//

import UIKit
import SVProgressHUD

class LoginAlertView: UIScrollView , AlertAnimationViewProtocol, CAAnimationDelegate{
    
    private var finishHandle : (() -> ())?
    
    private var unitHeight : CGFloat = 0
    
     var loginSuccessHandle : (() -> ())?
    
    
    private lazy var contentView: UIView = {
        let viewWidth = screenWidth - 16 * 2
        let viewHeight = viewWidth * 3 / 4
        unitHeight = viewHeight / 5
        let view = UIView(frame: CGRect(x: 16, y: 0, width: viewWidth, height: viewHeight))
        view.center = screenCenter
        view.backgroundColor = colorRGBA(red: 230, green: 230, blue: 230, alpha: 1)
        view.cornerRadius(radius: 5)
        return view
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: contentView.width, height: unitHeight))
        label.backgroundColor = clearColor
        label.textColor = blackColor
        label.text = "Login"
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 16)
        
        let line = CALayer()
        line.frame = CGRect(x: 0, y: label.height - 0.5, width: label.width, height: 0.5)
        line.backgroundColor = blackColor.cgColor
        label.layer.addSublayer(line)
        return label
    }()

    private lazy var accountTF: UITextField = {
        let tf = UITextField(frame: CGRect(x: 8, y: 0, width: contentView.width - 8 * 2, height: unitHeight - 16))
        tf.centerY = unitHeight / 2 + unitHeight
        tf.placeholder = "Input account"
        tf.backgroundColor = whiteColor
//        tf.cornerRadius(radius: tf.height / 2)
        tf.text = UserInfoManager.shared().account
        tf.textColor = blackColor
        tf.borderStyle = .roundedRect
        tf.font = UIFont.systemFont(ofSize: 16)
        tf.clearButtonMode = .whileEditing
        return tf
    }()
    
    private lazy var passwordTF: UITextField = {
        let tf = UITextField(frame: accountTF.frame)
        tf.centerY = unitHeight / 2 + unitHeight * 2
        tf.placeholder = "Input password"
        tf.backgroundColor = whiteColor
//        tf.cornerRadius(radius:  tf.height / 2)
        tf.text = UserInfoManager.shared().password
        tf.textColor = blackColor
        tf.borderStyle = .roundedRect
        tf.font = UIFont.systemFont(ofSize: 16)
        tf.isSecureTextEntry = true
        tf.clearButtonMode = .whileEditing
        return tf
    }()
    
    private lazy var savePasswordBtn: UIButton = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: contentView.width / 2, height: unitHeight))
        btn.bottom = contentView.height - unitHeight
        btn.backgroundColor = clearColor
        btn.setImage(UIImage(named: "savepassword_normal"), for: .normal)
        btn.setImage(UIImage(named: "savepassword_selected"), for: .selected)
        btn.setTitle("Save password", for: .normal)
        btn.setTitle("Save password", for: .selected)
        btn.setTitleColor(blackColor, for: .normal)
        btn.setTitleColor(blackColor, for: .selected)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btn.isSelected = UserInfoManager.shared().password != ""
        btn.addTarget(self, action: #selector(savePasswordAction(sender:)), for: .touchUpInside)
        return btn
    }()
    
    private lazy var cancelBtn: UIButton = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: contentView.width / 2, height: unitHeight  - 2))
        btn.bottom = contentView.height
        btn.backgroundColor = clearColor
        btn.setTitle("Cancel", for: .normal)
        btn.setTitleColor(blackColor, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        let topLine = CALayer()
        topLine.backgroundColor = blackColor.cgColor
        topLine.frame = CGRect(x: 0, y: 0, width: btn.width, height: 0.5)
        btn.layer.addSublayer(topLine)
        
        let rightLine = CALayer()
        rightLine.backgroundColor = blackColor.cgColor
        rightLine.frame = CGRect(x: btn.width - 0.25, y: 0, width: 0.25, height: btn.height)
        btn.layer.addSublayer(rightLine)
        
        btn.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
        return btn
    }()
    
    private lazy var finishBtn: UIButton = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: contentView.width / 2, height: unitHeight  - 2))
        btn.bottom = contentView.height
        btn.right = contentView.width
        btn.backgroundColor = clearColor
        btn.setTitle("Ok", for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btn.setTitleColor(blackColor, for: .normal)
        let topLine = CALayer()
        topLine.backgroundColor = blackColor.cgColor
        topLine.frame = CGRect(x: 0, y: 0, width: btn.width, height: 0.5)
        btn.layer.addSublayer(topLine)
        
        let rightLine = CALayer()
        rightLine.backgroundColor = blackColor.cgColor
        rightLine.frame = CGRect(x: 0, y: 0, width: 0.25, height: btn.height)
        btn.layer.addSublayer(rightLine)
        
        btn.addTarget(self, action: #selector(finishAction), for: .touchUpInside)
        return btn
    }()
    
    init() {
        super.init(frame: .zero)
        configView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func configView() {
        backgroundColor = clearColor
        frame = screenFrame
        addSubview(contentView)
        contentView.addSubview(titleLabel)
        contentView.addSubview(accountTF)
        contentView.addSubview(passwordTF)
        contentView.addSubview(savePasswordBtn)
        contentView.addSubview(cancelBtn)
        contentView.addSubview(finishBtn)
    }
    
    func showAnimation() {
        if #available(iOS 9.0, *) {
            let scaleA = CASpringAnimation(keyPath: "transform.scale")
            scaleA.isRemovedOnCompletion = false
            scaleA.fillMode = .forwards
            scaleA.mass = 0.6
            scaleA.stiffness = 100
            scaleA.damping = 6
            scaleA.initialVelocity = 10
            scaleA.fromValue = 0
            scaleA.toValue = 1
            scaleA.duration = 0.8
            contentView.layer.add(scaleA, forKey: "apearAnimation")
        } else {
            // Fallback on earlier versions
        }
        
    }
    
    func dismissAnimation(finish: @escaping (() -> ())) {
        let scaleA = CABasicAnimation(keyPath: "transform.scale")
        scaleA.isRemovedOnCompletion = false
        scaleA.fillMode = .forwards
        scaleA.fromValue = 1
        scaleA.toValue = 0
        scaleA.duration = 0.2
        scaleA.delegate = self
        contentView.layer.add(scaleA, forKey: "dismissAnimation")
        finishHandle = finish
    }
    
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        if flag == true {
            if finishHandle != nil {
                finishHandle!()
            }
        }
    }

    @objc private func savePasswordAction(sender:UIButton) {
        sender.isSelected = !sender.isSelected
    }
    
    @objc private func cancelAction() {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "CloseCustomAlertVC"), object: nil)
    }
    
    @objc private func finishAction() {
        guard !accountTF.text!.isEmpty else {
            SVProgressHUD.showError(withStatus: accountTF.placeholder)
            return
        }
        guard !passwordTF.text!.isEmpty else {
            SVProgressHUD.showError(withStatus: passwordTF.placeholder)
            return
        }
        
        net_login(account: accountTF.text!, password: passwordTF.text!, savePassword: savePasswordBtn.isSelected) {[weak self] in
            self!.cancelAction()
            if self?.loginSuccessHandle != nil {
                self?.loginSuccessHandle!()
            }
        }
    }
    
}
